package com.twu.biblioteca;

import com.twu.biblioteca.menuitem.MenuItem;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;

import static java.lang.Integer.parseInt;

/**
 * Created with IntelliJ IDEA.
 * User: Thoughtworker
 * Date: 8/21/13
 * Time: 10:55 AM
 * To change this template use File | Settings | File Templates.
 */
public class Menu {
    private HashMap<Integer, MenuItem> menuItemHashMap;
    private BufferedReader bufferedReader;
    private PrintStream printStream;
    private BibliotecaApp bibliotecaApp;

    public Menu(BufferedReader bufferedReader, PrintStream printStream, BibliotecaApp bibliotecaApp, HashMap<Integer, MenuItem> menuItemHashMap) {
        this.printStream = printStream;
        this.bufferedReader = bufferedReader;
        this.bibliotecaApp = bibliotecaApp;
        this.menuItemHashMap = menuItemHashMap;
    }

    public Menu(BufferedReader bufferedReader, HashMap<Integer, MenuItem> menuItemHashMap) {
        this.bufferedReader = bufferedReader;
        this.menuItemHashMap = menuItemHashMap;
    }

    public void welcome() {
        printStream.println("Welcome!");
    }

    public void showMenuOptions() {
        for (Map.Entry<Integer, MenuItem> menuItemEntry : menuItemHashMap.entrySet()) {
            printStream.println("[" + menuItemEntry.getKey() + "] "+ menuItemEntry.getValue());
        }
        printStream.println("Please press 0 to exit");
    }

    public int readMenuOption() {
        int result = -1;
        try {
            result = parseInt(bufferedReader.readLine());
            if (result < 0|| result > menuItemHashMap.size())
                throw new Exception();
        } catch (Exception e) {
            printStream.println("Select a valid option!!");
            result = -1;
        }
        return result;
    }

    public void processMenuOption(int option) {
        MenuItem menuItem = getMenuItemFromSelection(option);
        if(menuItem != null)
            getMenuItemFromSelection(option).execute();
    }

    public String readBookName() throws IOException {
        printStream.println("Enter name of book to reserve:");
        return bufferedReader.readLine();
    }

    public MenuItem getMenuItemFromSelection(int optionNumber) {
          return menuItemHashMap.get(optionNumber);
    }

    public void setMenuItems(HashMap<Integer,MenuItem> menuItems) {
        this.menuItemHashMap = menuItems;
    }

    public void setPrintStream(PrintStream printStream) {
        this.printStream = printStream;
    }

    public void setBibliotecaApp(BibliotecaApp bibliotecaApp) {
        this.bibliotecaApp = bibliotecaApp;
    }
}
